﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.ComponentModel;
using centraldba_dbrestore_utility.Data;

namespace centraldba_dbrestore_utility
{
    /// <summary>
    /// Interaction logic for Configure_ServerList.xaml
    /// </summary>
    public partial class Configure_ServerList : Window
    {
        List<MyServer> added, removed;
        SQLRecoveryManager_DB rman;

        #region " Constructor / Destructor "

        public Configure_ServerList()
        {
            InitializeComponent();

            // Initialize the interface to data
            rman = new SQLRecoveryManager_DB();
            added = new List<MyServer>();
            removed = new List<MyServer>();
        }
        ~Configure_ServerList()
        {
            added.Clear();
            removed.Clear();
            added = null;
            removed = null;
        }

        #endregion

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            lstDatabaseServers.ItemsSource = rman.GetPossibleSqlServers();
        }

        private void cmdSubmit_Click(object sender, RoutedEventArgs e)
        {
            Data.SQLRecoveryManager_DB rman = new Data.SQLRecoveryManager_DB();

            // Make newly selected servers visible
            foreach (Data.MyServer lbi in added)
            {
                rman.SetSqlServerVisibility(lbi.srv_server_name, true);
            }

            // Hide removed servers
            foreach (Data.MyServer lbi in removed)
            {
                rman.SetSqlServerVisibility(lbi.srv_server_name, false);
            }

            rman = null;

            this.Close();
        }

        private void lstDatabaseServers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Track added items
            foreach (Data.MyServer lbi in e.AddedItems)
            {
                if (!added.Contains(lbi) && !removed.Contains(lbi))
                    added.Add(lbi);

                else if (removed.Contains(lbi))
                    removed.Remove(lbi);
            }

            // Track removed items
            foreach (Data.MyServer lbi in e.RemovedItems)
            {
                if (!removed.Contains(lbi) && !added.Contains(lbi))
                    removed.Add(lbi);

                else if (added.Contains(lbi))
                    added.Remove(lbi);
            }
        }
    }
}
